/**
 * Created by Hata Kokoro on 6/28/2017.
 */
var Const = require('./const.js');
var PokerPlayer = require('../Poker/player').PokerPlayer;
var rules = require('./rule.js');
//var HandCards = require('./handCards').HandCards;
var Poker = require('../Poker/Poker');
var uTinsatance = require('./util');
var NN = require('../Poker/NN');

exports.BNCPlayer = PokerPlayer.extend({
    /*
    Member Variable
     */
    _bIsDealer:false,
    _iPowerRating:0,
    _selectedCards:[],
    _unSelectedCards:[],
    _ibetRate:0,
    _handsArray:[],
    _iBasePoint:1,
    _robDealer:-1, // 抢庄状态，-1/0/1 未选择/不抢/抢庄
    _startHandNum:5,
    init:function(uid,msg){
        this._super(uid,msg);
        this.robDealer=-1;
        this._selectedCards=[];
        this._iBasePoint=1;
    },
    /*
    Overridden Interface
     */
    getInitHandCardNeedNum:function(){
        return this._startHandNum;
    },

    getInfo:function(){
        var info = this._super();
        info.remainScore=this._stat.remainScore;
        return info;
    },

   onStartNewRound:function(){
       this._super();
       this._robDealer=-1;
       this._selectedCards=null;
       this._stat.roundPattern=Const.Pattern.NORMAL;
       this._bIsDealer=false;
       this._iPowerRating=0;
       this._handsArray=null;
       this._robDealer=-1;
   },
    /*
    Player's Interface
     */
    isSelectedCards:function(){
        if(this._selectedCards==null) return false;
        else return true;
    },

    setBasePoint: function (iPoint) {
        this._iBasePoint=iPoint;
    },

    getBasePoint: function () {
        return this._iBasePoint;
    },
    /**
     *
     * @param args
     */
    setRobDealer:function(args){
        this._robDealer=args;
    },
    /**
     *
     * @returns {*}
     */
    getRobDealer:function(){
        return this._robDealer;
    },
    /**
     *
     * @param arrCard
     */
    setSelectedCards:function(arrCard){
        this._selectedCards=[];
        logger.debug("SET SELECTED CARDS:  arrCard"+arrCard);
        if(!arrCard||arrCard.length==0){
            this._selectedCards=[];
            return true;
        }
        if(arrCard.length!=3){return false;}
        var cards=Poker.buildFromArray(arrCard);
        var allExist = true;
        //var allPoint=0;
        logger.debug(this._selectedCards);
        ExObject.eachKeyNum(cards,function(card,num){
            if(!card) allExist=false;
            if(this._handCards.getCardNum(card)<num) allExist=false;
        }.bind(this));
        if(allExist==true){
            arrCard.forEach(function(card){
                this._selectedCards.push(card);
            }.bind(this));
        }
        this._spiltCard();
        return true;
    },

    isSelectCards:function(){
        return (this._selectedCards)?true:false;
    },
    /***************************************************************
     * OVERRIDDEN INTERFACE
     ***************************************************************/
    getInfo:function() {
      var info = this._super();
        info.remainScore=this._stat.remainScore;
        return info;
    },

    getReconnectInfo: function (isSelf) {
        var info = this._super(isSelf);
        info.robDealer = this._robDealer;
        if (isSelf) {
            info.selectedCards = this._selectedCards;
        }
        info.selectNum = (this._selectedCards) ? this._selectedCards.length : -1;
    },

    getSettlementInfo: function () {
        var info = this._super();
        info.handCards = this._handCards;
        info.selectedCards = this._selectedCards;
        return info;
    },

    settlementPattern: function () {
        if(this._selectedCards) {
            var results = NN.calcNiuCards(this._handCards.getInitCards());
            this._selectedCards = (results.length > 0) ? results[0] : []
        }
        this._calcNiu()
    },

    onStartNewRound:function(){
        this._super();
        this._robDealer=-1;
        this._selectedCards=null;
        this._unSelectedCards=null;
        this._stat.roundPattern=Const.Pattern.NORMAL;
    },

    /**************************************************************
     * OVERRIDDEN INTERFACE
     * **************************************************************/

    getBestCombine:function() {
        var cTable = this._getAllCombine();
        logger.debug("cTABLE:");
        //var cvTable = this._getCombinePowerRating(cTable);
        //logger.debug("cvTable: "+cvTable);
       // var keys=Object.keys(cvTable);
        for(var i=0;i<10;i++){
                var sum=0;
                sum=this._getCombinePowerRating(cTable[i]);
                if(sum%10==0){
                    return cTable[i];
                }
        }
        return cTable[0];
    },


    sendRoundInfo: function () {
        var Info={
            combine:null,  // Selected Cards
            NiuLevel:-1,    //  Pattern
            unselected:null // unselected Cards
        };
        Info.combine= this.getBestCombine();
        logger.debug(Info.combine)
        this.setSelectedCards(Info.combine);
        Info.unselected=this._unSelectedCards;
        this._selectedCards=null;
        var hasNiu = rules.isNiu(Info.combine);
        logger.debug("--debug sendRoundInfo:")
        logger.debug("hasNiu: "+hasNiu);
        logger.debug("Combine: "+Info.combine);
        if(hasNiu) {
            Info.NiuLevel = rules.GetSecondPattern(this._unSelectedCards);
        }
        if(!hasNiu){
            Info.NiuLevel=0;
        }
        this.send("onGetHands",Info);
    },
    /**
     * get All combination of hand cards
     * @returns {Key-Value}
     * @private
     */
    _getAllCombine:function() {
        var CombinationTable = uTinsatance.Combination();
        logger.debug("CombineTable:"+CombinationTable)
        var arrHands = uTinsatance.Hands2Array(this._handCards.getCards());
        logger.debug("arrHands:"+arrHands);
        //Table for Combination-Value
        var cvTable = new Array();
        for (var i = 0; i < 10; i++) {
            cvTable[i]=new Array();
            for (var j = 0; j < 3; j++) {
                var index = CombinationTable[i][j]
                cvTable[i][j] = arrHands[index];
                //logger.debug(i+"cvTable["+i+"]["+j+"]:"+arrHands[index]);
            }
        }
        return cvTable;
    },
    /**
     * @param [Array]subCombine
     * @private
     */
    _getCombinePowerRating:function(subCombine) {
        var PR = rules.GetHandsPower(subCombine);
        return PR;
    },

    _spiltCard:function(){
        var arrHands = uTinsatance.Hands2Array(this._handCards.getCards());
        logger.debug("--debug:_spiltCard:");
        var unselected=[];
        for(var i=0;i<arrHands.length;i++) {
            var card = arrHands[i];
            if (this._selectedCards.indexOf(card) === -1) {
                unselected.push(card);
            }
        }
        this._unSelectedCards=unselected;
        logger.debug("unSelected: "+ this._unSelectedCards);
        logger.debug("--debug:_spiltCard:");
    },
    /*******************************************************
     * COPY FROM QZNN/player.js
     * ******************************************************/
    _calcNiu: function() {
        var selectCards = this._selectedCards;
        if (!selectCards || selectCards.length == 0) {
            this._stat.roundPattern = Const.Pattern.NONE;
            return;
        }

        var allCardsArr = this._handCards.getInitCards();
        var otherPoints = 0;
        allCardsArr.forEach(function(card) {
            if (selectCards.indexOf(card) == -1) {
                otherPoints += NN.getPoint(card);
            }
        });

        var nPoint = otherPoints%NN.BASE;
        var pattern = Const.Pattern.NONE;

        if (nPoint == 0) {
            pattern = Const.Pattern.NN;
            var minPoint = Poker.Point.MAX;
            var maxPoint = Poker.Point.MIN;
            allCardsArr.forEach(function(card) {
                var point = Poker.getPoint(card);
                minPoint = Math.min(minPoint, point);
                maxPoint = Math.max(maxPoint, point);
            });

            if (minPoint >= Poker.Point.J && maxPoint <= Poker.Point.K) {
                pattern = Const.Pattern.JIN;
            }
        } else {
            pattern = Const.Pattern['N' + nPoint];
        }

        this._stat.roundPattern = pattern;
    },

    _getMaxCard: function() {
        var maxCard = 0;
        var selectCards = this._selectedCards;
        var allCardsArr = this._handCards.getInitCards();

        allCardsArr.forEach(function(card) {
            if (selectCards && selectCards.indexOf(card) == -1) {
                if (!maxCard || NN.cardLT(card, maxCard)) {
                    maxCard = card;
                }
            }
        });

        return maxCard;
    },

});